﻿using Telerik.Windows.Controls;
using TruckScale.Models;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.ViewModels
{
  public class ChangePwdViewModel : ViewModelBase
  {
    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    public string LoginId { get; set; }
    public string InfoBar { get; set; }
    public string OldPwd { get; set; }
    public string NewPwd { get; set; }
    public string ConfirmPwd { get; set; }
    public DelegateCommand SaveCommand { get; private set; }
    public ChangePwdViewModel()
    {
      LoginId = Global._currentUser?.LoginId;

      if (LoginId == null)
      {
        InfoBar = "请先登录再修改密码！";
      }

      SaveCommand = new DelegateCommand(OnSaveCommandExecuted, OnCanSaveExecuted);
    }

    private bool OnCanSaveExecuted(object obj)
    {
      return !string.IsNullOrEmpty(Global._currentUser?.LoginId);
    }

    private void OnSaveCommandExecuted(object obj)
    {
      if ((string.IsNullOrEmpty(OldPwd) && string.IsNullOrEmpty(Global._currentUser?.LoginPwd))
        || OldPwd == Global._currentUser?.LoginPwd)
      {
        if (string.IsNullOrEmpty(NewPwd))
        {
          InfoBar = "请输入新密码";
          return;
        }
        if (!NewPwd.Equals(ConfirmPwd))
        {
          InfoBar = "两次密码不一致，请重新输入。";
          return;
        }
        else
        {
          Global._currentUser.LoginPwd = NewPwd;
          UserModel.UpdateUser(Global._currentUser);
          InfoBar = "密码修改成功，请用新密码登录！";
          SetLog($"用户 {Global._currentUser?.UserName} 修改登录密码", LogType.OperationLogger);
        }
      }
      else
      {
        InfoBar = "原密码错误！";
      }
    }
  }
}
